package com.szl.yeb.common;

import com.szl.yeb.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Objects;

/**
 * 全局异常处理
 *
 * @author szl
 * @since 2022-08-24 16:21:30
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     *
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<Object> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error("数据库相关错误", ex);
        return R.errMsg("数据库相关错误");
    }

    /**
     * 异常处理方法
     *
     * @return
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public R<Object> exceptionHandler(DuplicateKeyException ex) {
        log.error("数据库相关错误", ex);
        //获取重复值
        String message = ex.getMessage();
        assert message != null;
        if(message.contains("Duplicate entry '")){
            int from = message.indexOf("Duplicate entry '") + "Duplicate entry '".length();
            int to = message.indexOf("' for key 'name'");
            String duplicateEntry = message.substring(from, to);
            return R.errMsg(duplicateEntry + "已存在");
        }
        return R.errMsg("数据库相关错误");
    }


    @ExceptionHandler(DataIntegrityViolationException.class)
    public R<Object> exceptionHandler(DataIntegrityViolationException ex) {
        if(Objects.requireNonNull(ex.getMessage()).contains("a foreign key constraint fails (`yeb`.`t_menu_role`")){
            log.error("存在角色使用该菜单，无法删除", ex);
            return R.errMsg("存在角色使用该菜单，无法删除");
        }
        log.error("传入数据有误", ex);
        return R.errMsg("传入数据有误");
    }

    /**
     * 异常处理方法
     *
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<Object> exceptionHandler(CustomException ex) {
        log.error("出现异常：", ex);
        return R.errMsg(ex.getMessage());
    }

    /**
     * 异常处理方法
     *
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R<Object> exceptionHandler(Exception ex) {
        log.error("出现异常：", ex);
        return R.errMsg("未知错误");
    }

}
